package com.icehand.sentinel.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhoujunmei
 * @date 2020年6月17日
 */
@Component
@Slf4j
public class CustomUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        String result = "";
        if (e instanceof FlowException) {
            result = "FlowException";
        } else if(e instanceof ParamFlowException) {
            result = "ParamFlowException";
        } else if(e instanceof DegradeException) {
            result = "DegradeException";
        } else if(e instanceof SystemBlockException) {
            result = "SystemBlockException";
        } else if(e instanceof AuthorityException) {
            result = "AuthorityException";
        }

        httpServletResponse.setHeader("Content-Type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(result);
    }
}
